using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace v6502
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private static RAM ram;

        delegate void updateRegisterCallback(string val, string reg);

        public void updateRegister(string val, string reg)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new updateRegisterCallback(updateRegister), new object[] { val, reg });
            }
            else
            {
                switch (reg)
                {
                    case "AC":
                        this.txtAC.Text = val;
                        break;
                    case "SP":
                        this.txtSP.Text = val;
                        break;
                    case "PC":
                        this.txtPC.Text = val;
                        break;
                    case "Y":
                        this.txtY.Text = val;
                        break;
                    case "X":
                        this.txtX.Text = val;
                        break;
                }
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            ram = new RAM(0xFFFF);
            CPU cpu = new CPU(ram);
            InstructionSet instructionSet = new InstructionSet();
            Assmebler assembler = new Assmebler(instructionSet, ram);
            assembler.Assemble(txtAsm.Text);
            //ram.write(0xFE, 0x77);
            //ram.write(0x200, 0x77);
            //ram.write(0x400, 0x77);
            ram.print(0x600, 30);
            cpu.run();
            //ram.print(0x200, 2);
            //ram.print(0x300, 2);
            //ram.print(0x400, 2);
            //ram.print(0x500, 2);
        }

        private void Test_Click(object sender, EventArgs e)
        {
            bool[] statusRegister = new bool[8];
            for (int i = 0; i < statusRegister.Length; i++)
                statusRegister[i] = false;
            statusRegister[3] = true;
            statusRegister[6] = true;
            int procStat = 0;
            for (int i = 0; i < 8; i++)
            {
                if (statusRegister[i] == true)
                    procStat += (int)Math.Pow(2, i);
            }

            int tmpStack = procStat;
            for (int i = 0; i < 8; i++)
            {
                if ((tmpStack & (int)Math.Pow(2, i)) == (int)Math.Pow(2, i))
                    statusRegister[i] = true;
            }
            for (int i = 0; i < statusRegister.Length; i++)
                Console.WriteLine("statusRegister[" + i.ToString() + "] = " + statusRegister[i]);
        }
    }
}